import { createStore } from "vuex";
import { userinfo } from "../axios/api.js";
import { myFinancial } from "../axios/community.js";
import WebSocketTool from "@/utils/websocket";
// import list from "@/mock/shijiebei.json";
// import peilv from "@/mock/peilv.json";
// import bisaiguanlian from "@/mock/bisaiguanlian.json";

let lan = window.localStorage.getItem("lan") || "zh";
let userAccount = window.localStorage.getItem("aimverse-account"); //用户账号??????
let userInfoData = window.localStorage.getItem("aimverse-userInfo"); //用户信息
let editNftData = window.localStorage.getItem("editNftData"); //编辑创建nft数据
let accessToken = window.localStorage.getItem("aimverse-accessToken"); //token
let searchinput = window.localStorage.getItem("aimverse-searchinput"); //token
let detailid = window.localStorage.getItem("detailid"); //detailid
let updateModelInfo = window.localStorage.getItem("updateModelInfo")
  ? JSON.parse(window.localStorage.getItem("updateModelInfo"))
  : ""; //模型修改文件
let Recommendyou = window.localStorage.getItem("Recommendyou"); //detailid
let infomessage = window.localStorage.getItem("infomessage"); //评论数据
let lazyWidth = window.localStorage.getItem("lazyWidth"); //瀑布流宽度
let searchHistory = window.localStorage.getItem("searchHistory"); //搜索历史记录
let moduleID = window.localStorage.getItem("moduleID"); //模型ID
let mjToken = window.localStorage.getItem("mjToken"); //mjtoken
let unreadNum = window.localStorage.getItem("mjToken"); // 未读消息
let websoketnums = window.localStorage.getItem("websoketnums"); // 未读消息
let xiaoxiNum = window.localStorage.getItem("xiaoxiNum"); // 未读消息

let globalConfig = window.localStorage.getItem("globalConfig")
  ? JSON.parse(window.localStorage.getItem("globalConfig"))
  : ""; //全局配置
let personlist = window.localStorage.getItem("personlist"); // 消息记录

let whichConfigData = window.localStorage.getItem("whichConfigData")
  ? JSON.parse(window.localStorage.getItem("whichConfigData"))
  : ""; //表情包配置
let quxiaobanner = window.localStorage.getItem("quxiaobanner"); // 未读消息
let codeinfo = window.localStorage.getItem("codeinfo"); // 二维码信息
let minToken = window.localStorage.getItem("minToken"); // 社区token
let minUserInfo = window.localStorage.getItem("minUserInfo"); // 社区token
let userData = window.localStorage.getItem("userData")
  ? JSON.parse(window.localStorage.getItem("userData"))
  : ""; // 收集用户的信息
let headindex = window.localStorage.getItem("headindex") || 0; // 头部index

let minUserBalance = window.localStorage.getItem("minUserBalance")
  ? JSON.parse(window.localStorage.getItem("minUserBalance"))
  : ""; // 社区token
let Socket = window.localStorage.getItem("Socket") || null; // Socket

export default createStore({
  state: {
    ws: null, // websorket实例
    headindex,
    lan: lan, //语言
    account: userAccount, //用户账号
    hideHeaderBg: false, //公用头背景颜色是否透明
    headerFixed: false, //公用头是否固定定位
    userInfo: userInfoData ? JSON.parse(userInfoData) : "", //用户信息
    editNftData: editNftData ? JSON.parse(editNftData) : "", //编辑nft创建信息
    accessToken, //token
    searchinput,
    detailid,
    unreadNum: unreadNum ? unreadNum : 0,
    updateModelInfo,
    infomessage,
    Recommendyou, // 为你推荐
    lazyWidth, //瀑布流宽度
    searchHistory: searchHistory ? JSON.parse(searchHistory) : "", //搜索历史记录
    mjToken,
    showBottom: false,
    moduleID,
    quxiaobanner, // 取消顶部banner
    // globalConfig, //全局配置
    whichConfigData, //表情包配置

    personlist: personlist != "undefined" ? JSON.parse(personlist) : "", // 社区列表
    globalConfig,
    websoketnums,
    xiaoxiNum,
    codeinfo,
    minToken,
    minUserInfo: minUserInfo != "undefined" ? JSON.parse(minUserInfo) : "", //社区用户信息
    userData,
    minUserBalance, //用户余额
    Socket: null,
    // userData: {
    //   id: "", // 用户id
    //   history: [], // 搜索历史记录
    //   like: [], // 喜欢
    //   Collect: [], // 收藏
    //   dwellTime: {}, // 浏览时长
    //   behavior: [], // 交互行为
    //   snsCollect: [], // 社区喜爱博主圈子关注
    //   snsLike: [], // 社区点赞，评论
    // },
  },
  getters: {
    // 用戶信息
    getUserInfo(state) {
      if (state.userInfo) {
        return JSON.parse(state.userInfo);
      } else {
        return "";
      }
    },
  },
  mutations: {
    contentSocket(state, data) {
      state.Socket = data;
      // window.localStorage.setItem("Socket", data);
    },
    // 头部index
    setheadindex(state, data) {
      state.headindex = data;
      window.localStorage.setItem("headindex", data);
    },

    // 存储用户余额
    setMinUserBalance(state, data) {
      state.minUserBalance = data;
      window.localStorage.setItem("minUserBalance", JSON.stringify(data));
    },

    // // 清除用户信息
    // removeUserDataInfo(state,data) {
    //   window.localStorage.removeItem("userData");
    // },
    // 收集用户数据
    saveUserDataInfo(state, { type, data }) {
      let userData;
      if (!window.localStorage.getItem("userData")) {
        userData = {
          history: [], // 搜索历史记录
          dwellTime: [], // 浏览时长
          behavior: [], // 交互行为
        };
      } else {
        userData = JSON.parse(window.localStorage.getItem("userData"));
      }
      switch (type) {
        case "dwellTime":
          userData.dwellTime.push(data);
          break;
        case "behavior":
          userData.behavior.push(data);
          break;
        case "history":
          userData.history.push(data);
          break;
      }
      window.localStorage.setItem("userData", JSON.stringify(userData));
    },
    // 存储社区用户信息
    saveminUserInfo(state, data) {
      state.minUserInfo = data;
      window.localStorage.setItem("minUserInfo", JSON.stringify(data));
    },

    // 存储社区token
    setminToken(state, data) {
      state.minToken = data;
      window.localStorage.setItem("minToken", data);
      setTimeout(() => {
        // console.log("进入");
        const ws = new WebSocketTool("wss://sns.desai.art/wss");
        let datas = {};
        datas.device = "mp";
        datas.mode = "bind";
        datas.played = "";
        datas.token = data;
        ws.connect(datas); // 连接
      }, 1000);
    },
    // 二维码数据
    setcodeinfo(state, data) {
      state.codeinfo = data;
      window.localStorage.setItem("codeinfo", JSON.stringify(data));
    },
    // 消息数量
    setquxiaobanner(state, data) {
      state.quxiaobanner = data;
      window.localStorage.setItem("quxiaobanner", JSON.stringify(data));
    },
    // 消息数量
    setxiaoxiNum(state, data) {
      // console.log(data);
      // if (type == 0) {
      state.xiaoxiNum = data;
      // } else {
      //   state.xiaoxiNum++;
      // }
      // console.log(state.xiaoxiNum);
      window.localStorage.setItem("xiaoxiNum", state.xiaoxiNum);
    },
    // websocket数量
    setwebsoketnums(state, data) {
      state.websoketnums++;
      // console.log(state.websoketnums);
      window.localStorage.setItem("websoketnums", JSON.stringify(data));
    },
    // 存储消息记录
    setPersonlist(state, data) {
      // let personlistOld = window.localStorage.getItem("personlist");
      // if (!personlistOld) {
      state.personlist = data;
      // console.log(data);
      window.localStorage.setItem("personlist", JSON.stringify(data));
      //   return;
      // }
      // let personlistOldArr = JSON.parse(personlistOld);
      // var merged = data.slice();
      // for (var i = 0; i < personlistOldArr.length; i++) {
      //   var element = personlistOldArr[i];
      //   var id = element.user.id;

      //   // 检查是否存在具有相同 id 的元素
      //   var existingElement = merged.find(function (item) {
      //     return item.user.id === id;
      //   });

      //   // 如果不存在具有相同 id 的元素，则将该元素添加到合并数组中
      //   if (!existingElement) {
      //     merged.push(element);
      //   }
      // }
      // window.localStorage.setItem("personlist", JSON.stringify(merged));
    },
    // 存储未读消息数量
    setunreadNum(state, data) {
      state.unreadNum = data;
      window.localStorage.setItem("unreadNum", data);
    },
    // 存储全局配置
    setGlobalConfig(state, data) {
      state.globalConfig = data;
      window.localStorage.setItem("globalConfig", JSON.stringify(data));
    },

    // 存储表情配置
    setWhichConfigData(state, data) {
      state.whichConfigData = data;
      window.localStorage.setItem("whichConfigData", JSON.stringify(data));
    },

    //保存模型ID
    setmoduleID(state, data) {
      state.moduleID = data;
      window.localStorage.setItem("moduleID", data);
    },
    // 修改显示隐藏底部备案
    setShowBottom(state, data) {
      state.showBottom = data;
    },

    // 存储mjtoken
    setMjToken(state, data) {
      state.mjToken = data;
      window.localStorage.setItem("mjToken", data);
    },

    // 存储搜索记录
    setSearchHistory(state, data) {
      let storageHistory = window.localStorage.getItem("searchHistory");
      let list = storageHistory ? JSON.parse(storageHistory) : ""; //搜索历史记录
      if (list) {
        let hasidx = list.indexOf(data);
        if (hasidx > -1) {
          let idxData = list.splice(hasidx, 1);
          list.unshift(idxData[0]);
        } else {
          list.unshift(data);
          if (list.length > 10) {
            list.pop();
          }
        }
      } else {
        list = [];
        list.push(data);
      }
      state.searchHistory = list;
      window.localStorage.setItem("searchHistory", JSON.stringify(list));
    },

    // 删除搜索记录
    removeSearchHistory(state, index) {
      let storageHistory = window.localStorage.getItem("searchHistory");
      let list = storageHistory ? JSON.parse(storageHistory) : ""; //搜索历史记录
      list.splice(index, 1);
      if (!list.length) {
        state.searchHistory = "";
        window.localStorage.setItem("searchHistory", "");
      } else {
        state.searchHistory = list;
        window.localStorage.setItem("searchHistory", JSON.stringify(list));
      }
    },

    // 为你推荐
    setinfoRecommendyou(state, data) {
      state.Recommendyou = data;
      window.localStorage.setItem("Recommendyou", data);
    },
    // 评论数据
    setinfomessage(state, data) {
      state.infomessage = data;
      window.localStorage.setItem("infomessage", data);
    },
    // 搜索框内
    setdetailid(state, data) {
      state.detailid = data;
      window.localStorage.setItem("detailid", data);
    },
    // 搜索框内
    setsearchData(state, data) {
      state.searchinput = data;
      window.localStorage.setItem("aimverse-searchinput", data);
    },
    // 清除修改nft内容的data
    clearEditNftData(state, data) {
      state.editNftData = "";
      window.localStorage.removeItem("editNftData");
    },

    // 存储修改nft内容的data
    setEditNftData(state, data) {
      state.editNftData = data;
      window.localStorage.setItem("editNftData", JSON.stringify(data));
    },

    // 修改用户余额
    setUserBalance(state, data) {
      state.userBalance = data;
    },

    // 修改语言
    setLan(state, data) {
      state.lan = data;
      window.localStorage.setItem("lan", data);
    },

    //存储用户地址
    saveAccount(state, data) {
      state.account = data;
      window.localStorage.setItem("aimverse-account", data);
    },

    // 存储用户信息
    saveUserInfo(state, data) {
      state.userInfo = data;
      window.localStorage.setItem("aimverse-userInfo", JSON.stringify(data));
    },

    // 存储tokne
    saveToken(state, data) {
      state.accessToken = data;
      window.localStorage.setItem("aimverse-accessToken", data);
    },

    // 移除用户信息/地址
    outLogin(state, data) {
      state.account = "";
      state.userInfo = "";
      state.accessToken = "";
      state.searchinput = "";
      state.detailid = "";
      state.mjToken = "";
      state.minToken = "";
      state.globalConfig = "";
      state.minUserInfo = "";
      state.whichConfigData = "";
      state.userData = "";
      state.minUserBalance = "";
      window.localStorage.removeItem("userData");
      window.localStorage.removeItem("whichConfigData");
      window.localStorage.removeItem("globalConfig");
      window.localStorage.removeItem("minUserInfo");
      window.localStorage.removeItem("aimverse-account");
      window.localStorage.removeItem("aimverse-userInfo");
      window.localStorage.removeItem("aimverse-accessToken");
      window.localStorage.removeItem("aimverse-searchinput");
      window.localStorage.removeItem("detailid");
      window.localStorage.removeItem("mjToken");
      window.localStorage.removeItem("minToken");
      window.localStorage.removeItem("minUserBalance");
    },

    // 修改头部背景色
    setHideHeaderBg(state, data) {
      state.hideHeaderBg = data;
    },

    // 修改头部是否固定定位
    setHeaderFixed(state, data) {
      state.headerFixed = data;
    },

    // 修改更新模型文件数据
    setUpdateModelInfo(state, data) {
      state.updateModelInfo = data;
      window.localStorage.setItem("updateModelInfo", JSON.stringify(data));
    },

    // 清除更新模型文件数据
    delUpdateModelInfo(state, data) {
      state.updateModelInfo = "";
      window.localStorage.removeItem("updateModelInfo");
    },

    // 修改瀑布流宽度
    setLazyWidth(state, data) {
      state.lazyWidth = data;
      window.localStorage.setItem("lazyWidth", data);
    },
  },
  actions: {
    // 获取最新用户信息并更新
    updateUserInfo(context) {
      userinfo().then((res) => {
        res.data.mininfo = res.data.miniData;
        context.commit("saveUserInfo", res.data);
      });
    },

    // 更新用户余额
    updataMinUserBalance(context) {
      myFinancial({
        id: "?setUserid=0",
      }).then((res) => {
        let resultData = res.data;
        let obj = {
          coins: resultData.coins.total,
          balance: resultData.financial ? resultData.financial.balance : 0,
        };
        context.commit("setMinUserBalance", obj);
      });
    },
  },
});
